<template>
  <n-modal
      v-model:show="props.modalData.show"
      class="custom-card"
      preset="card"
      :style="{ 'min-width': '600px', 'max-width': '60vw' }"
      title="上传图片"
      :bordered="false"
      :segmented="{
      content: 'hard',
      footer: 'hard'
    }"
  >
    <n-form :model="form" label-placement="left" :label-width="90">
      <n-form-item label="选择分组" path="groupId">
        <n-select v-model:value="form.groupId" :options="mediaGroupList" filterable/>
      </n-form-item>

      <n-form-item label="上传图片" path="mediaUrlList">
        <n-upload
            action="http://127.0.0.1:8080/file/upload"
            list-type="image-card"
            :custom-request="handleChange"

        >
        </n-upload>
        <n-modal
            v-model:show="showModal"
            preset="card"
            style="width: 600px"
            title="预览"
        >
          <n-image :src="previewImageUrl"/>
        </n-modal>
      </n-form-item>
    </n-form>

    <template #footer>
      <n-space justify="end">
        <n-button @click="handleClose">取消</n-button>
        <x-button type="primary" :loading="loading" @click="handleSave">确定</x-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
import {NButton, NForm, NFormItem, NImage, NModal, NSelect, NSpace, NUpload, UploadFileInfo} from 'naive-ui'
import XButton from '@/components/x-button.vue'
import {ref, watchEffect} from 'vue'
import {useMediaStore} from "@/store/media";
import {reqSaveMedia} from "@/api";

const emits = defineEmits(['success'])
const showModal = ref(false)
const previewImageUrl = ref('')
const mediaStore = useMediaStore()
const props = defineProps({
  modalData: {
    type: Object,
    required: true
  }
})
const loading = ref(false)
const form = ref({
  groupId: props.modalData.groupId === -1 ? null : props.modalData.groupId,
  mediaList: <any>[],
})
const mediaGroupList = ref([])

function handlePreview(file: UploadFileInfo) {
  console.log("preview")
  const {url} = file
  previewImageUrl.value = url as string
  showModal.value = true
}

function handleChange({
                        file,
                        data,
                        headers,
                        withCredentials,
                        action,
                        onFinish,
                        onError,
                        onProgress
                      }) {
  const formData = new FormData()
  if (data) {
    Object.keys(data).forEach(key => {
      formData.append(key, data[key])
    })
  }
}

function handleFinish({file, event}: {
  file: UploadFileInfo
  event?: ProgressEvent
}) {
  console.log("finish", file)
  const {errno, data} = JSON.parse((event?.target as XMLHttpRequest).response)
  form.value.mediaList.push({
    mediaName: file.name,
    mediaUrl: 'http://127.0.0.1:8080/static/' + data
  })
  file.url = 'http://127.0.0.1:8080/static/' + data
  return file
}

function handleRemoveImage({file, fileList}: { file: UploadFileInfo, fileList: Array<UploadFileInfo> }) {
  console.log("remove")
  form.value.mediaList = form.value.mediaList.filter(item => item.mediaUrl !== file.url)
}

function handleClose() {
  props.modalData.show = false
}

async function handleSave() {
  if (form.value.mediaList.length <= 0) {
    return message.warning(`请上传图片`)
  }
  await reqSaveMedia(form.value)
  props.modalData.show = false
  emits('success')
}

watchEffect(() => {
  if (props.modalData.show) {
    mediaGroupList.value = mediaStore.getGroupOptionList()
  }
})
</script>

<style scoped lang="scss"></style>
